"""
Helper functions

All names available in this module will be available under the Pylons h object.
"""
from webhelpers import *
from pylons.helpers import log, abort
from pylons.i18n import get_lang, set_lang
from pylons import session
from bumblebee.lib.auth import get_user, SignedIn, HasPermission, InGroup, NotAuthorized
from bumblebee import model

def flash(msg):
    session['flash'] = msg
    session.save()

def selector(expr, true_result, false_result):
    "Drop-in replacement for ternary expressions"
    if expr:
        return true_result
    return false_result

def get_object_or_404(model, **kw):
    """
    Returns object, or raises a 404 Not Found is object is not in db 
    Example: user = get_object_or_404(model.User, id = 1)
    """
    obj = model.get_by(**kw)
    if obj is None:
        abort(404)
    return obj

def signed_in():
    "Checks if user logged in"
    try:
        SignedIn().check()
        return True
    except NotAuthorized:
        return False

def in_group(name):
    "Checks if user a member of a group"
    try:
        InGroup(name).check()
        return True
    except NotAuthorized:
        return False

def has_permission(perm):
    "Checks if current user has given permission"
    try:
        HasPermission(perm).check()
        return True
    except NotAuthorized:
        return False

def user_options(selected=None):
    users = [(u.username, u.id) for u in model.User.select()]
    return options_for_select(users, selected)

def impact_options(selected=None):
    impact_codes = [(v, k) for k, v in model.impact_codes.iteritems()]
    return options_for_select(impact_codes, selected)

def chance_options(selected=None):
    chance_codes = [(v, k) for k, v in model.chance_codes.iteritems()]
    return options_for_select(chance_codes, selected)

def status_options(selected=None):
    status_codes = [(v, k) for k, v in model.status_codes.iteritems()]
    return options_for_select(status_codes, selected)
